﻿using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.SignalR.Client;
using System.ComponentModel.DataAnnotations;
using TrackSystem.Entities.RequestFeature;
using TrackSystem.IO.Models;
using TrackSystem.IO.Sensors;

namespace TrackSystem.UI.Server.Pages.IOControl
{
    public partial class IOControlPage
    {
        [Required]
        private HubConnection? _hubIo;

        private string _message = "无信息";

        private List<IOUnit>? lstPorts;

        private string? sensorName;

        private SensorUnit? sensor;

        [Required]
        private PageParameter? pageOptions = new PageParameter()
        {
            CurrentPage = 1,
            PageSize = 3,
            Filter = ""
        };

        /// <summary>
        /// 首次渲染
        /// </summary>
        /// <param name="firstRender"></param>
        /// <returns></returns>
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                try
                {
                    // 建立SIGNALR连接
                    _hubIo = new HubConnectionBuilder()
                        .WithUrl("http://localhost:5000/ioctlhub")
                        .WithAutomaticReconnect(new[] { TimeSpan.Zero, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(10) })
                        .Build();

                    await _hubIo.StartAsync();

                    // 注册查询端口状态响应函数
                    _hubIo.On<List<IOUnit>>("HandleChannelStatus", (tt) =>
                    {
                        lstPorts = tt;
                        InvokeAsync(StateHasChanged);
                    });

                    _hubIo.On<List<IOUnit>, PageParameter>("HandlePagedChannelStatus", (tt, opt) =>
                    {
                        lstPorts = tt;
                        pageOptions = opt;
                        InvokeAsync(StateHasChanged);
                    });

                    // 注册初始化传感器响应函数
                    _hubIo.On<string>("HandleInitSensors", (tt) =>
                    {
                        _message = tt;
                        InvokeAsync(StateHasChanged);
                    });

                    _hubIo.On<SensorUnit>("HandleSensorByName", (tt) =>
                    {
                        sensor = tt;
                        InvokeAsync(StateHasChanged);
                    });




                    var timer = new System.Timers.Timer(1000);
                    timer.Elapsed += async (s, e) =>
                    {
                        try
                        {
                            //await _hubIo.SendAsync("AcquireChannelMessage");
                            await _hubIo.SendAsync("AcquirePagedChannelMessage", pageOptions);
                            await _hubIo.SendAsync("AcquireSensorByName", sensorName);
                        }
                        catch (Exception ex)
                        {
                            _message = ex.Message;
                            await InvokeAsync(StateHasChanged);
                        }
                    };
                    timer.Start();

                    _message = "SignalR连接成功";
                }
                catch (Exception ex)
                {
                    _message = ex.Message;
                }
                StateHasChanged();
            }
        }

        /// <summary>
        /// 初始化传感器
        /// </summary>
        /// <returns></returns>
        private async Task BtnInitSensors()
        {
            try
            {
                if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
                {
                    await _hubIo.SendAsync("InitialRegs");
                    await _hubIo.SendAsync("InitialSensors");
                }
            }
            catch (Exception ex)
            {
                _message = ex.Message;
                await InvokeAsync(StateHasChanged);
            }
        }

        /// <summary>
        /// 卸载所有传感器
        /// </summary>
        /// <returns></returns>
        private async Task BtnUnloadSensors()
        {
            try
            {
                sensorName = "";
                if (_hubIo != null && _hubIo.State == HubConnectionState.Connected)
                    await _hubIo.SendAsync("UnloadSensors");
            }
            catch (Exception ex)
            {
                _message = ex.Message;
                await InvokeAsync(StateHasChanged);
            }
        }

        /// <summary>
        /// 传感器选中回调函数
        /// </summary>
        /// <param name="snr"></param>
        /// <returns></returns>
        private Task SelectedSensorChanged(string  snrName)
        {
            if (sensorName == snrName)
                sensorName = null;
            else
                sensorName = snrName;

            StateHasChanged();
            return Task.CompletedTask;
        }

        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        private Task OnPageClick(int pageIndex)
        {
            pageOptions.CurrentPage = pageIndex;
            return Task.CompletedTask;
        }
    }
}
